<template>
  <div class="foods">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜品管理</span>
          <div>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索菜品"
              style="width: 200px; margin-right: 10px"
              @keyup.enter="searchFoods"
            >
              <template #append>
                <el-button @click="searchFoods">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              添加菜品
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="foods" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="菜品名称" width="150" />
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="80">
          <template #default="{ row }">
            <el-tag :type="getDifficultyType(row.difficulty)">
              {{ getDifficultyText(row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cookTime" label="时长" width="80">
          <template #default="{ row }">
            {{ row.cookTime }}分钟
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="权重" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewFood(row)">查看</el-button>
            <el-button size="small" @click="editFood(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteFood(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingId ? '编辑菜品' : '添加菜品'"
      width="800px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入菜品描述"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="form.price" :precision="2" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制作难度" prop="difficulty">
              <el-select v-model="form.difficulty" style="width: 100%">
                <el-option label="简单" :value="1" />
                <el-option label="中等" :value="2" />
                <el-option label="困难" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制作时间" prop="cookTime">
              <el-input-number v-model="form.cookTime" :min="0" style="width: 100%" />
              <span style="margin-left: 8px">分钟</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="食材清单" prop="ingredients">
          <el-input
            v-model="form.ingredients"
            type="textarea"
            :rows="3"
            placeholder="请输入食材清单，用逗号分隔"
          />
        </el-form-item>
        
        <el-form-item label="制作步骤" prop="steps">
          <el-input
            v-model="form.steps"
            type="textarea"
            :rows="4"
            placeholder="请输入制作步骤"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标签" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入标签，用逗号分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="权重" prop="weight">
              <el-input-number v-model="form.weight" :min="1" :max="10" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="图片URL" prop="imageUrl">
          <el-input v-model="form.imageUrl" placeholder="请输入图片URL" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveFood" :loading="saving">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="菜品详情" width="600px">
      <div v-if="currentFood" class="food-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="菜品名称">{{ currentFood.name }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ currentFood.categoryName }}</el-descriptions-item>
          <el-descriptions-item label="价格">¥{{ currentFood.price }}</el-descriptions-item>
          <el-descriptions-item label="制作难度">{{ getDifficultyText(currentFood.difficulty) }}</el-descriptions-item>
          <el-descriptions-item label="制作时间">{{ currentFood.cookTime }}分钟</el-descriptions-item>
          <el-descriptions-item label="权重">{{ currentFood.weight }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ currentFood.description }}</el-descriptions-item>
          <el-descriptions-item label="食材清单" :span="2">{{ currentFood.ingredients }}</el-descriptions-item>
          <el-descriptions-item label="制作步骤" :span="2">
            <div style="white-space: pre-line;">{{ currentFood.steps }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="标签" :span="2">{{ currentFood.tags }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { getFoodsByPage, createFood, updateFood, deleteFood, searchFoods } from '../api/food'
import { getEnabledCategories } from '../api/category'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Foods',
  setup() {
    const foods = ref([])
    const categories = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const viewDialogVisible = ref(false)
    const saving = ref(false)
    const editingId = ref(null)
    const currentFood = ref(null)
    const formRef = ref(null)
    const searchKeyword = ref('')
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    const form = ref({
      name: '',
      description: '',
      imageUrl: '',
      categoryId: null,
      price: 0,
      difficulty: 1,
      cookTime: 0,
      ingredients: '',
      steps: '',
      tags: '',
      status: 1,
      weight: 1
    })
    
    const rules = {
      name: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
      categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }]
    }
    
    const loadFoods = async () => {
      loading.value = true
      try {
        const res = await getFoodsByPage(currentPage.value, pageSize.value)
        foods.value = res.data.records
        total.value = res.data.total
      } catch (error) {
        ElMessage.error('加载菜品失败')
      } finally {
        loading.value = false
      }
    }
    
    const loadCategories = async () => {
      try {
        const res = await getEnabledCategories()
        categories.value = res.data
      } catch (error) {
        ElMessage.error('加载分类失败')
      }
    }
    
    const searchFoods = async () => {
      if (!searchKeyword.value.trim()) {
        loadFoods()
        return
      }
      
      loading.value = true
      try {
        const res = await searchFoods(searchKeyword.value)
        foods.value = res.data
        total.value = res.data.length
      } catch (error) {
        ElMessage.error('搜索失败')
      } finally {
        loading.value = false
      }
    }
    
    const showAddDialog = () => {
      editingId.value = null
      form.value = {
        name: '',
        description: '',
        imageUrl: '',
        categoryId: null,
        price: 0,
        difficulty: 1,
        cookTime: 0,
        ingredients: '',
        steps: '',
        tags: '',
        status: 1,
        weight: 1
      }
      dialogVisible.value = true
    }
    
    const editFood = (row) => {
      editingId.value = row.id
      form.value = { ...row }
      dialogVisible.value = true
    }
    
    const viewFood = (row) => {
      currentFood.value = row
      viewDialogVisible.value = true
    }
    
    const saveFood = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        saving.value = true
        
        if (editingId.value) {
          await updateFood(editingId.value, form.value)
          ElMessage.success('更新成功')
        } else {
          await createFood(form.value)
          ElMessage.success('创建成功')
        }
        
        dialogVisible.value = false
        loadFoods()
      } catch (error) {
        console.error('保存失败:', error)
      } finally {
        saving.value = false
      }
    }
    
    const deleteFood = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除菜品"${row.name}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await deleteFood(row.id)
        ElMessage.success('删除成功')
        loadFoods()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
      loadFoods()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadFoods()
    }
    
    const getDifficultyType = (difficulty) => {
      const typeMap = { 1: 'success', 2: 'warning', 3: 'danger' }
      return typeMap[difficulty] || 'info'
    }
    
    const getDifficultyText = (difficulty) => {
      const textMap = { 1: '简单', 2: '中等', 3: '困难' }
      return textMap[difficulty] || '未知'
    }
    
    onMounted(() => {
      loadFoods()
      loadCategories()
    })
    
    return {
      foods,
      categories,
      loading,
      dialogVisible,
      viewDialogVisible,
      saving,
      editingId,
      currentFood,
      form,
      rules,
      formRef,
      searchKeyword,
      currentPage,
      pageSize,
      total,
      showAddDialog,
      editFood,
      viewFood,
      saveFood,
      deleteFood,
      searchFoods,
      handleSizeChange,
      handleCurrentChange,
      getDifficultyType,
      getDifficultyText
    }
  }
}
</script>

<style scoped>
.foods {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.food-detail {
  padding: 0;
}
</style>